package megrez.common.jpa;

import javax.persistence.criteria.From;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;

import lombok.experimental.UtilityClass;

/**
 * 自定义
 * 
 * <b>
 * 参考：https://dimitr.im/writing-dynamic-queries-with-spring-data-jpa
 * 
 * @author Lucky Yang
 * @since 0.0.1
 */
@UtilityClass
public class SpecificationHelper {

    public Join<?, ?> rightJoin(From<?, ?> from, String attribute) {
        return join(from, attribute, JoinType.RIGHT);
    }

    public Join<?, ?> leftJoin(From<?, ?> from, String attribute) {
        return join(from, attribute, JoinType.LEFT);
    }

    public Join<?, ?> innerJoin(From<?, ?> from, String attribute) {
        return join(from, attribute, JoinType.INNER);
    }

    private Join<?, ?> join(From<?, ?> from, String attribute, JoinType joinType) {
        for (Join<?, ?> join : from.getJoins()) {
            boolean sameName = join.getAttribute().getName().equals(attribute);
            if (sameName && join.getJoinType().equals(joinType)) {
                return join;
            }
        }
        return from.join(attribute, joinType);
    }
}
